package com.exposit.books.web;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.exposit.books.domain.Buyer;
import com.exposit.books.service.GenreService;
import com.exposit.books.service.LogInService;

@Controller
public class LoginController {
	
	@Autowired
	private LogInService logInService;
	
	@Autowired
	private GenreService genreService;
	
	@RequestMapping(value = "/shop", method = RequestMethod.GET)
	public String shop(Model model) {
		return "shop";
	}
	
	@RequestMapping(value = "/login", method = { RequestMethod.POST })
	public ModelAndView login(
		@RequestParam(value = "login", required = true) String login,
		@RequestParam(value = "password", required = true) String password,
		HttpServletRequest request, HttpSession session) {
		
		ModelAndView mav = new ModelAndView();

		try
		{
			Buyer user = logInService.logIn(login, password);
			user.getOrders();
			session.setAttribute("user", user);
			mav = new ModelAndView("redirect:/profile/"+user.getId());
		}
		catch(Exception e)
		{
			mav.addObject("loginError", e.getMessage().toString());
			mav.setViewName("shop");
		}
 
		return mav;
	}
	
	@RequestMapping(value = "/registration", method = { RequestMethod.POST })
	public ModelAndView registration(
		@RequestParam(value = "login", required = true) String login,
		@RequestParam(value = "password", required = true) String password,
		@RequestParam(value = "confirm password", required = true) String confirmPassword,
		@RequestParam(value = "name", required = true) String name,
		@RequestParam(value = "surname", required = true) String surname,
		HttpServletRequest request, HttpSession session) {
		
		ModelAndView mav = new ModelAndView();

		try
		{
			if (password.compareTo(confirmPassword) != 0)
				throw new Exception("Passwords don't match!");
			Buyer user = logInService.registration(login, password, name, surname);
			session.setAttribute("user", user);
			mav = new ModelAndView("redirect:/profile/"+user.getId());
		}
		catch(Exception e)
		{
			mav.addObject("registrationError", e.getMessage().toString());
			mav.setViewName("shop");
		}
 
		return mav;
	}
	
	@RequestMapping(value = "/logout")
	public ModelAndView logout(HttpSession session) {

		ModelAndView model = new ModelAndView();
		model.setViewName("shop");
		
		session.setAttribute("user", null);
		session.invalidate();
		
		return model;
	}
}
